package libs

import (
	"github.com/gomodule/redigo/redis"
	"time"
)

var (
	pool *redis.Pool
)

func init()  {
	pool = &redis.Pool{
		MaxIdle: 3,
		MaxActive: 5,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial(
				"tcp",
				config.Redis.Host,
				redis.DialReadTimeout(time.Duration(1000) * time.Millisecond),
				redis.DialWriteTimeout(time.Duration(1000) * time.Millisecond),
				redis.DialConnectTimeout(time.Duration(1000) * time.Millisecond),
				redis.DialDatabase(config.Redis.Select),
			)
			if err != nil {
				return nil, err
			}


			return c, err
		},
	}
}

func GetRedis() redis.Conn {
	if pool == nil {
		return nil
	}
	return pool.Get()
}

// key set
func RedisSet(key string, value interface{}, expire int) error {
	db := GetRedis()
	_, err := db.Do("SETEX", config.Redis.Prefix + key, expire, value)

	return err
}

// key get
func RedisGet(key string) (interface{}, error) {
	db := GetRedis()
	retry, err := db.Do("GET", config.Redis.Prefix + key)

	return retry, err
}
